package com.timothy.android;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.timothy.answer.BaseStationSelection;
import com.timothy.question.BaseStation;
import com.timothy.service.CommunicationService;
import com.timothy.service.MessageSenderUtil;
import com.timothy.statistics.LoginBuilder;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class BaseStations extends BaseActivity {
	private final String LOG_TAG = "BaseStations";
	private ListView mylist = null;
	private EditText baseID = null;
	private EditText loginId = null;
	private EditText loginPwd = null;
	
	private Button refreshBtn = null;
	private Button connectBtn = null;
	
	private String hostIp = null;
	private int hostPort ;
	private String baseStationStr = null;
	
	ArrayList<HashMap<String, Object>> listItem;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.basestations);
		//set screen orientation to portrait
//		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		Bundle bundle = this.getIntent().getExtras();
		hostIp = bundle.getString("hostIp");
		hostPort = bundle.getInt("hostPort");
		baseStationStr = bundle.getString("baseStationStr");
		
		List<BaseStation> bsList = LoginBuilder.parseBaseStation(baseStationStr);
		
		//initial components
		mylist = (ListView) findViewById(R.id.myListView);
		baseID = (EditText) findViewById(R.id.baseIdTxt);
		baseID.clearFocus();
		
		loginId = (EditText) findViewById(R.id.loginIdTxt);
		loginPwd = (EditText) findViewById(R.id.loginPwdTxt);
		
		//get information from history, if exist, set history information to components
		String preUserid = sharedPreferences.getString("userid", null);  
		String preUserpassword = sharedPreferences.getString("userpassword", null);
		Log.i(LOG_TAG, "load history from sharedPreferences:userid="+preUserid);
		Log.i(LOG_TAG, "load history from sharedPreferences:password="+preUserpassword);
		
		if(preUserid!=null) loginId.setText(preUserid);
		if(preUserpassword!= null) loginPwd.setText(preUserpassword);
		
		refreshBtn = (Button) findViewById(R.id.refreshBtn);
		connectBtn = (Button) findViewById(R.id.connectBtn);
		
        //生成动态数组，加入数据
        listItem = new ArrayList<HashMap<String, Object>>();
        
        for(int i=0;i<bsList.size();i++){
        	HashMap<String, Object> map = new HashMap<String, Object>();
        	BaseStation bs = bsList.get(i);
        	map.put("hostName", bs.getName());
        	listItem.add(map);
        }
		
        SimpleAdapter listItemAdapter = new SimpleAdapter(this,listItem,//数据源 
                R.layout.basestations_item,//ListItem的XML实现
                new String[] {"hostName","port","hostAddr"},
        		new int[] {R.id.hostNameTV,R.id.portTV,R.id.hostAddrTV}
        );
        mylist.setAdapter(listItemAdapter);
        mylist.setOnItemClickListener(new OnItemClickListener(){
        	@Override
			public void onItemClick(AdapterView<?> adapter, View view, int arg2,
					long arg3) {
        		
        		for(int i=0;i<adapter.getChildCount();i++){
        			adapter.getChildAt(i).setBackgroundColor(Color.parseColor("#ffaaff"));
        		}
        		
        		TextView hostName = (TextView) view.findViewById(R.id.hostNameTV); 
        		
        		view.setBackgroundColor(Color.parseColor("#8290d8"));
				baseID.setText(hostName.getText().toString());
				
			}      	
        });
        
        refreshBtn = (Button) this.findViewById(R.id.refreshBtn);
        refreshBtn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				
				//get wifi service 
		        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
		        //check wifi is enabled 
		        if (!wifiManager.isWifiEnabled()) { 
		        	ShowDialog("Wifi is not available!");
		        	return;
		        } 
		        
		        MessageSenderUtil.PHONE_IP = getWifiIP();
		        if ( MessageSenderUtil.PHONE_IP==null || MessageSenderUtil.PHONE_IP.equals("") || MessageSenderUtil.PHONE_IP.equals("0.0.0.0")) { 
		        	ShowDialog("Your WIFI NetWork is not available!");
		        	return;
		        } 
		        
//				if(!MessageSender.sendMessage( MessageSender.Get_Base_Stations) ) {
//					ShowDialog("Can not login Server!");
//				}
				
				String message = MessageSenderUtil.addHeader(MessageSenderUtil.Get_Base_Stations);
				if(! sendMessage(message)) {
					ShowDialog("Can not Connect,please try again!");
				}
				
			}			
		});
        
        //login into baseStation
        connectBtn = (Button) this.findViewById(R.id.connectBtn);
        connectBtn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				String bsNameString = baseID.getText().toString();
				String loginIdString = loginId.getText().toString();
				String loginPwdString = loginPwd.getText().toString();
				
				Bundle bundle = new Bundle();
				
				bundle.putString("baseStationName", bsNameString);
				bundle.putString("loginId", loginIdString);
				bundle.putString("loginPwd", loginPwdString);
			    
				//set baseStation information
				final BaseStationSelection bss = new BaseStationSelection();
				bss.setBaseStationName(bsNameString);
				bss.setUserName(loginIdString);
				bss.setPassword(loginPwdString);
				
				//Send Phone Information to PC
				if(baseID!=null&&baseID.getText().toString().length()>0){
					//send...
//					if(!MessageSender.sendBaseStationSelection(bss) ) {
//						ShowDialog("Can not Connect,please try again!");
//					}
					String message = MessageSenderUtil.sendBaseStationSelection(bss);
					if(!sendMessage(MessageSenderUtil.addHeader(message))) {
						ShowDialog("Can not Connect,please try again!");
					}
					
				}else{
					ShowDialog("Please choose a Base Station!");
				}
				 
			}			
		});
        
	}
	
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		setTitle("You Clicked "+item.getItemId()+""); 
		return super.onContextItemSelected(item);
	}

	@Override
	protected void processMessage(int what, String content) {
		Log.i(LOG_TAG, "processMessage:");
		Log.i(LOG_TAG, "what:" + what);
		Log.i(LOG_TAG, "content:" + content);

		if (CommunicationService.MSG_CONNECT_BASE != what)
			return;

		if ("successfully".equals(content)) {
			Log.i(LOG_TAG, "successfully...");
			
			Log.i(LOG_TAG, BaseStations.this.toString());
			
			//pop dialog to remind user save information
			AlertDialog.Builder builder = new AlertDialog.Builder(BaseStations.this);
			builder.setMessage(getResources().getString(R.string.wheter_to_remember))
					.setCancelable(false)
					.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int id) {
									// save information to local
									SharedPreferences.Editor editor = sharedPreferences.edit();
									editor.putString("userid", loginId.getText().toString());
									editor.putString("userpassword",loginPwd.getText().toString());
									editor.commit();
									
									//go to home page
									Intent intent = new Intent();
									intent.putExtra("baseStationStr", baseStationStr);
									intent.putExtra("hostIp", hostIp);
									intent.putExtra("hostPort", hostPort);
									intent.setClass(getBaseContext(), HomeActivity.class);
									finish();//finish current activity
									startActivity(intent);
								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int id) {
									dialog.cancel();
									
									//go to home page
									Intent intent = new Intent();
									intent.putExtra("baseStationStr", baseStationStr);
									intent.putExtra("hostIp", hostIp);
									intent.putExtra("hostPort", hostPort);
									intent.setClass(getBaseContext(), HomeActivity.class);
									finish();//finish current activity
									startActivity(intent);
								}
							});
			builder.show();
			
			
			
		} else if("IPOutOfRange".equals(content)){
			Toast.makeText(getBaseContext(), R.string.msg_connect_base_out_of_range,Toast.LENGTH_SHORT).show();	
		} else{
			Toast.makeText(getBaseContext(), R.string.msg_connect_base_pwd_invalid,Toast.LENGTH_SHORT).show();			
		}
		
		if( CommunicationService.MSG_BASE_STATION == what ) {
			Intent intent = new Intent();
			intent.putExtra("value", content);
			intent.setClass( getBaseContext(), BaseStations.class);
			finish();//finish current activity
			startActivity(intent);
		}
		
	}
	
	@Override
	protected void onRestart() {
		Log.i(LOG_TAG, "onRestart()...");
		super.onRestart();
	}


	@Override
	protected void onResume() {
		Log.i(LOG_TAG, "onResume()...");
		super.onResume();
	}


	@Override
	protected void onStart() {
		Log.i(LOG_TAG, "onStart()...");
		super.onStart();
	}


	@Override
	protected void onStop() {
		Log.i(LOG_TAG, "onStop()...");
		super.onStop();
	}


	private String getWifiIP() {
		// get wifi service
		WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		// is wifi enabled
		if (!wifiManager.isWifiEnabled()) {
			wifiManager.setWifiEnabled(true);
		}
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int ipAddress = wifiInfo.getIpAddress();
		String ip = intToIp(ipAddress);
		Log.i("BaseStations","WIFI IP:" + ip);
		return ip;
	}
	
	private String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
				+ "." + (i >> 24 & 0xFF);
	}
	

	
}